package com.mxpio.erp.equipment.controller;

import com.mxpio.erp.common.enums.EquipmentEnums;
import com.mxpio.erp.common.equipment.entity.EquipmentCalibration;
import com.mxpio.erp.common.equipment.service.EquipmentCalibrationService;
import com.mxpio.erp.common.equipment.service.EquipmentEqpBasicsService;
import com.mxpioframework.common.util.SpringUtil;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.system.service.SnRuleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Slf4j
@Tag(name = "EquipmentCalibrationController", description = "设备检定接口")
@RestController
@RequestMapping("/erp/equipment/calibration/")
public class EquipmentCalibrationController {

    @Autowired
    private EquipmentCalibrationService calibrationService;

    @Autowired
    private EquipmentEqpBasicsService basicsService;

    @GetMapping("list")
    @Operation(summary = "设备检定列表", description = "获取检定列表（无分页）", method = "GET")
    public Result<List<EquipmentCalibration>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<EquipmentCalibration> list = calibrationService.list(EquipmentCalibration.class, criteria);
        return Result.OK(list);
    }

    @GetMapping("page")
    @Operation(summary = "设备检定列表", description = "获取检定列表（分页）", method = "GET")
    public Result<Page<EquipmentCalibration>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<EquipmentCalibration> pageResult = calibrationService.listPage(EquipmentCalibration.class, page, criteria);
        return Result.OK(pageResult);
    }

    @RequestMapping("add")
    @Operation(summary = "添加并保存设备检定信息", description = "添加并保存设备检定信息")
    public Result<EquipmentCalibration> add(@RequestBody EquipmentCalibration equipmentCalibration) {
        if (StringUtils.isBlank(equipmentCalibration.getCalCode())){
            SnRuleService snRuleService = SpringUtil.getBean(SnRuleService.class);
            String  CalCode= "QCI";
            String bizNo = (String) snRuleService.execute(CalCode + "#####", null);
            equipmentCalibration.setCalCode(bizNo);
        }
//            @Override
//            public boolean beforeInsert (CrudContext context){
//                Object o = context.getEntity();
//                if (o instanceof EquipmentEvaluateDetail){
//                    EquipmentEvaluate parent = context.getParent();
//                    ((EquipmentEvaluateDetail) o).setDetailId(parent.getId());
//                }
//                return true;
//            }
        EquipmentCalibration save = calibrationService.save(equipmentCalibration);
        calibrationService.listExecute(equipmentCalibration);
        return Result.OK(save);
    }

    @PutMapping("edit")
    @Operation(summary = "编辑设备检定", description = "编辑设备检定", method = "PUT")
    public Result<EquipmentCalibration> edit(@RequestBody EquipmentCalibration equipmentCalibration) {
        calibrationService.update(equipmentCalibration);
        return Result.OK(equipmentCalibration);
    }

    @DeleteMapping("remove/{ids}")
    @Operation(summary = "根据id删除设备检定表", description = "删除设备SOP,多个id用英文逗号分隔", method = "DELETE")
    public Result<EquipmentCalibration> remove(@PathVariable(name = "ids", required = true) String ids) {
        String[] id = ids.split(",");
        for(String key : id){
            calibrationService.delete(EquipmentCalibration.class, key);
        }
        return Result.OK();
    }


    @PutMapping("execute/{calCode}")
    @Operation(summary = "为当前检定订单生成实际开始时间并修改状态", description = "为当前检定订单生成实际开始时间并修改状态", method = "PUT")
    public Result<EquipmentCalibration> execute(@PathVariable(name = "calCode", required = true) String calCode){
        EquipmentCalibration equipmentCalibration = calibrationService.getById(EquipmentCalibration.class, calCode);
        if (equipmentCalibration.getExecutionStatus().equals(EquipmentEnums.Project.LSSUED.getCode())){
            return calibrationService.updateTime(equipmentCalibration, EquipmentEnums.Calibration.IMPROGRESS);
        }else {
            return Result.error("该项目不在下达中, 不可执行");
        }
    }

    @PutMapping("submit/{calCode}")
    @Operation(summary = "下达检定单", description = "根据calCode下达检定单", method = "PUT")
    public Result<EquipmentCalibration> submit(@PathVariable(name = "calCode", required = true) String calCode){
        EquipmentCalibration equipmentCalibration = calibrationService.getById(EquipmentCalibration.class, calCode);
        if (equipmentCalibration.getExecutionStatus().equals(EquipmentEnums.Project.PLAN.getCode())){
            return calibrationService.updateCalStatus(equipmentCalibration, EquipmentEnums.Calibration.LSSUED);
        }else {
            return Result.error("未找到需要下达的项目");
        }
    }

    @PutMapping("complete")
    @Operation(summary = "完成检定单", description = "根据calCode完成检定单", method = "PUT")
    public Result<EquipmentCalibration> complete(@RequestBody EquipmentCalibration equipmentCalibration){
        calibrationService.finish(equipmentCalibration);
        return Result.OK();
    }

    @PutMapping("completes/{calCodes}")
    @Operation(summary = "批量完成检定单", description = "批量完成检定单",method = "PUT")
    public Result<EquipmentCalibration> completes (@PathVariable(name = "calCodes", required = true) String calCodes,
                                                   @RequestBody EquipmentCalibration equipmentCalibration){
//        @PathVariable(name = "testUnit", required = true) String  testUnit,
//        @PathVariable(name = "testResult", required = true) String testResult
        calibrationService.batchCompletion(calCodes,equipmentCalibration);
        return Result.OK();
    }
}
